package per.dg.keepalive.multiprocess.multiprocessmessenger

import android.app.ActivityManager
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import per.dg.keepalive.R

class MessengerClientActivity : AppCompatActivity() {

    private val TAG = "MessengerClientActivity"

//    服务端 Messenger
    lateinit var messenger : Messenger

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_messenger_client)
    }

    fun onClick(view: View) {

        startAndBindService()
        
        Thread(object : Runnable {
            override fun run() {
                while (true){
                    var isRunningForService = isRunningForService(this@MessengerClientActivity, "per.dg.keepalive.multiprocess.multiprocessmessenger.MultiProcessMessengerService")

                    Log.e(TAG, "run: "+isRunningForService )

                    if(!isRunningForService){
                        startAndBindService()
                    }

                    Thread.sleep(1000)
                }
            }
        }).start()
    }

    fun startAndBindService(){
        //        绑定服务
        startService(Intent(this, MultiProcessMessengerService::class.java))
        bindService(Intent(this, MultiProcessMessengerService::class.java), serviceConnection, Service.BIND_AUTO_CREATE)
    }

    var serviceConnection : ServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            //通过服务端返回的Binder创建Messenger
            messenger = Messenger(service)

            Thread(object : Runnable {
                override fun run() {
                    sendDataToService(1)
                }
            }).start()
            Thread(object : Runnable {
                override fun run() {
                    sendDataToService(2)
                }
            }).start()
            Thread(object : Runnable {
                override fun run() {
                    sendDataToService(3)
                }
            }).start()
        }
    }

//    发送数据到fuwuduan
    fun sendDataToService(i : Int){
        //创建消息，通过Bundle传递数据
        val message: Message = Message.obtain(null, MESSAGE_FROM_CLIENT)
        val bundle = Bundle()
        bundle.putString("msg", "hello service,this is client")
        message.setData(bundle)

        message.replyTo = mClientMessenger;

        try {
            //向服务端发送消息
            messenger.send(message)
        } catch (e: RemoteException) {
            e.printStackTrace()
        }
    }

    var mMessengerHandler : Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when(msg.what){
                MESSAGE_FROM_SERVICE -> {
                    Log.e(TAG, "receive message from service:" + msg.getData().getString("msg"));
                }
                else -> {
                    super.handleMessage(msg)
                }
            }
        }
    }

    val mClientMessenger : Messenger = Messenger(mMessengerHandler)

    fun isRunningForService(context : Context, serviceName : String ) : Boolean {
        // 获取Activity管理者对象
        var manager : ActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        // 获取正在运行的服务（此处设置最多取1000个）
        var runningServices : List<ActivityManager.RunningServiceInfo>  = manager
                .getRunningServices(1000);
        // 遍历，若存在名字和传入的serviceName的一致则说明存在
        for (runningServiceInfo : ActivityManager.RunningServiceInfo in runningServices) {
            if (runningServiceInfo.service.getClassName().equals(serviceName)) {
                return true;
            }
        }

        return false;
    }
    
    override fun onDestroy() {
        super.onDestroy()
        unbindService(serviceConnection)
    }
}